<template>
  <div class="audio-player" :class="fold ? 'fold' : ''">
    <svg-icon
      iconName="zhankai"
      class="fold-icon hover animate__animated animate__fadeIn"
      v-if="fold"
      @click="fold = false"
    ></svg-icon>
    <svg-icon
      iconName="shouqi"
      class="fold-icon hover animate__animated animate__fadeIn"
      v-else
      @click="fold = true"
    ></svg-icon>
    <!-- :src="require(`${list[index].url}`) closeIcon -->
    <audio controls ref="audio-player" style="display: none"></audio>
    <div class="audio-mock-player" v-if="isShowAudioPlayer">
      <!--  播放进度条 -->
      <el-slider
        class="progress"
        v-model="sliderVal"
        :format-tooltip="formatTooltip"
        :min="sliderMin"
        :max="sliderMax"
        @change="spliderSelect"
      />
      <!-- 左边 -->
      <div class="left">
        <div class="song-infor">
          <!-- 歌手图片 -->
          <div class="song-img"><x-img class="x-img" :src="list[index]?.songerImg"></x-img></div>
          <div class="song-right">
            <div v-if="list.length" class="song-name">
              {{ `${list[index]?.name} - ${list[index]?.singer}` }}
            </div>
            <div v-else class="song-name">没有播放的音乐</div>
            <div class="bottom">
              <span class="current">{{ currentTime || '00:00' }}</span>
              <span class="duration">/{{ duration || '00:00' }}</span>
            </div>
          </div>
        </div>
      </div>
      <!-- 中间 -->
      <div class="center">
        <drop-down
          :list="[
            { icon: 'cycleList', label: '列表循环' },
            { icon: 'cycleOne', label: '单曲循环' },
            { icon: 'random', label: '随机播放' }
          ]"
          placement="top"
          @click="playModel = $event.icon"
        >
          <svg-icon :iconName="playModel" className="play-model"></svg-icon>
        </drop-down>
        <!-- 上一首 -->
        <svg-icon iconName="previous" className="preicon hover" @click="musicPlay('pre')"></svg-icon>
        <!-- "暂停" : "播放" -->
        <svg-icon
          :iconName="play ? 'pauseIcon' : 'playIcon'"
          className="play-sty hover"
          @click="musicPlay('play')"
        ></svg-icon>

        <svg-icon iconName="next" className="preicon hover" @click="musicPlay('next')"></svg-icon>
        <div class="vulumn hover" @click="changeVolumns">
          <el-popover placement="top" trigger="hover" width="50px" popper-class="aa">
            <el-slider
              vertical
              height="100px"
              :step="0.1"
              v-model="sliderValVolumn"
              :format-tooltip="formatTooltipVolumn"
              :min="0"
              :max="1"
              @change="spliderSelectVolumn"
            />
            <template #reference>
              <svg-icon
                style="width: 20px; height: 20px"
                :iconName="sliderValVolumn ? 'vulumn' : 'mutedIcon'"
              ></svg-icon>
            </template>
          </el-popover>
        </div>
      </div>
      <!-- 右边 -->
      <div class="right">
        <svg-icon
          :iconName="collect ? 'collect2' : 'collect1'"
          className="collect hover"
          @click="handleCollcet"
        ></svg-icon>
        <svg-icon iconName="downLoad" className="collect hover" @click="handleDown"></svg-icon>
        <!-- 播放列表 -->
        <lay-dropdown class="top-end" placement="top-end" updateAtScroll>
          <svg-icon iconName="menu" className="collect hover"></svg-icon>
          <template #content>
            <play-list
              :list="list"
              style="width: 300px; height: 500px"
              @itemClick="musicPlayById"
            ></play-list>
          </template>
        </lay-dropdown>
      </div>
    </div>
  </div>
</template>

<script>
import {get} from '@/http/index'
import { reactive, toRefs, getCurrentInstance, watch, ref } from 'vue'
import { useStore } from 'vuex'
import { userInfor } from '@/hooks/userInfor'
export default {
  emits: ['update:isShowAudioPlayer'],
  props: {
    // 显示隐藏
    isShowAudioPlayer: {
      default: true
    },
    // 播放列表
    list: {
      default: function () {
        return [
          //数据格式
          {
            id: 1,
            name: '大田后生仔',
            url: './assets/杨辰 - 大田后生仔 (DJ版).mp3',
            cover: 'ChenYou',
            singer: '杨辰',
            songerImg: ''
          }
        ]
      }
    }
    //  播放索引
    // index
  },
  setup(props, { emit }) {
    const pageInstance = getCurrentInstance()
    const store=useStore()
    const exceedOne1=ref(false)
    const exceedOne2=ref(false)
    const exceedOne3=ref(false)
    const _data = reactive({
      // playIcon: require("./asset/play.png"),
      // plozeIcon: require("./asset/ploze.png"),
      // vulumnIcon: require("./asset/vulumn.png"),
      // mutedIcon: require("./asset/muted3.png"),
      collect: false,
      playModel: 'cycleList', //播放类型
      box: undefined,
      index: 0, // 当前播放的音乐素质索引
      play: false, // 播放状态，true为正在播放
      sliderVal: 0, // 这个对接当前时长。
      sliderMin: 0,
      sliderMax: 0, // 这个对接总时长。
      sliderValVolumn: 0.5, // 音量
      copySliderValVolumn: 0.5,
      duration: undefined, // 音乐总时长
      currentTime: undefined, //当前播放时长
      fold: false // 是否折叠
    })
    function init() {
      return new Promise((resolve, reject) => {
        _data.box = pageInstance.refs['audio-player']
        _data.box.src = process.env.VUE_APP_IMG_BASE + props.list[_data.index]?.url
        // console.log(_data.box, '音频播放器DOM')

        //  this.duration  =  this.formatTime(this.box.duration)
        // 绑定三个触发方法
        // 当时长有变化时触发，由"NaN"变为实际时长也算
        _data.box.ondurationchange = function () {
          // console.log('时长发生了变化')
          console.log(_data.box.duration)
          // that.
          // that.duration  =  that.formatTime(that.box.duration)
          _data.sliderMax = Math.floor(_data.box.duration)
          updateTime()
        }
        // 当前数据可用是触发
        _data.box.oncanplay = function () {
          resolve()
          // console.log('已经可以播放了')
        }
        // 播放位置发送改变时触发。
        _data.box.ontimeupdate = function () {
          console.log('播放位置发送了变动')
          updateTime()
        }
        // 音频播放完毕
        _data.box.onended = function () {
          // console.log('播放完毕，谢谢收听')
          exceedOne1.value=false
          exceedOne2.value=false
          exceedOne3.value=false
          if (_data.playModel === 'cycleList') {
            // 列表循环
            musicPlay('next')
          } else if (_data.playModel === 'cycleOne') {
            // 单曲循环
            musicPlayById()
          } else if (_data.playModel === 'random') {
            // 随机
            let randomIndex = Math.floor(Math.random() * props.list.length)
            _data.index = randomIndex
            musicPlayById()
          }
        }
        // 音频播放完毕
        _data.box.onerror = function () {
          reject()
          // console.log('加载出错！')
        }
      })
    }
    watch(
      () => props.list.length,
      () => {
        init().then(() => {
          _data.play = false
        }).catch(()=>{})
      }
    )
    function changeVolumns() {
      // 静音切换
      if (_data.sliderValVolumn > 0) {
        _data.sliderValVolumn = 0
      } else {
        _data.sliderValVolumn = _data.copySliderValVolumn
      }
    }
    function musicPlayById(id) {
      if(id) _data.index = props.list.findIndex(item => item.id === id)
      init().then(() => {
        _data.play = true
        _data.box.play()
      })
    }
    function musicPlay(flag) {
      switch (flag) {
        case 'pre':
          if (props.list[_data.index - 1]) {
            _data.box.src = props.list[_data.index - 1].url
            _data.index -= 1
          } else {
            _data.box.src = props.list[props.list.length - 1].url
            _data.index = props.list.length - 1
          }
          init().then(() => {
            _data.play = true
            _data.box.play()
          })
          break
        case 'play':
          _data.play = !_data.play
          if (_data.play) {
            _data.box.play()
          } else {
            _data.box.pause()
          }
          break
        case 'next':
          if (props.list[_data.index + 1]) {
            _data.box.src = props.list[_data.index + 1].url
            _data.index += 1
          } else {
            _data.box.src = props.list[0].url
            _data.index = 0
          }
          init().then(() => {
            _data.play = true
            _data.box.play()
          })
          break
      }
    }
    function formatTooltip(val) {
      // 格式化毫秒数，由于组件提示为纯数字，所以这里需要将数字转化为我们所需要的的格式，string类型的。'03:45',
      const time = formatTime(val)
      return `${time.min}:${time.sec}`
    }
    function formatTooltipVolumn(val) {
      return val * 100 + '%'
    }
    function spliderSelectVolumn() {
      _data.box.volume = _data.sliderValVolumn
      // 备份音量
      _data.copySliderValVolumn = _data.sliderValVolumn
    }
    function updateTime() {
      const total = formatTime(_data.box.duration)
      const current = formatTime(_data.box.currentTime)
      _data.duration = `${total.min}:${total.sec}`
      _data.currentTime = `${current.min}:${current.sec}`
      
      // 升级
      addGrade(current,total)
      
      // 值为xx.xxxxx 需要取整
      _data.sliderVal = Math.floor(_data.box.currentTime)
    }
    function addGrade(current,total){
      if(!userInfor.value.userNo) return
      let flag= (parseInt(current.min)*60+parseInt(current.sec))/(parseInt(total.min)*60+parseInt(total.sec))
      if(flag>1/3&&!exceedOne1.value){
        store.dispatch('addGrade')
        exceedOne1.value=true
      }else if(flag>2/3&&!exceedOne2.value){
        store.dispatch('addGrade')
        exceedOne2.value=true
      }else if(parseInt(flag)==1 && !exceedOne3.value){
        store.dispatch('addGrade')
        exceedOne3.value=true
      }
    }
    function formatTime(time) {
      // 格式化毫秒，返回String型分秒对象

      if (!time) return { min: '00', sec: '00' }
      return {
        min: Math.floor(time / 60)
          .toString()
          .padStart(2, '0'),
        sec: Math.floor(time % 60)
          .toString()
          .padStart(2, '0')
      }
    }
    function closeAudioPlay() {
      emit('update:isShowAudioPlayer', false)
    }
    function spliderSelect() {
      // 滑块松动后触发。更新当前时长，
      // 时长发生变动会init里的方法进行更新数据
      _data.box.currentTime = _data.sliderVal
    }
    function handleCollcet() {
      _data.collect = !_data.collect
    }
    function handleDown(){
      get(props.list[_data.index].url,{},{
        responseType: 'blob'
      }).then(res=>{
        let href= window.URL.createObjectURL(new Blob([res]))
        let a= document.createElement('a')
        a.style = 'display: none';
        a.download=`${props.list[_data.index].name}.${props.list[_data.index].url.split('.')[1]}`
        a.href=href
        document.body.appendChild(a)
        a.click()
        document.body.removeChild(a)
      })
    }
    return {
      ...toRefs(_data),
      exceedOne1,
      exceedOne2,
      changeVolumns,
      musicPlay,
      formatTooltip,
      formatTooltipVolumn,
      spliderSelectVolumn,
      updateTime,
      formatTime,
      closeAudioPlay,
      spliderSelect,
      handleCollcet,
      musicPlayById,
      handleDown
    }
  }
}
</script>

<style lang="scss" scoped>
.hover {
  &:hover {
    cursor: pointer;
  }
}
.fold {
  transform: translateY(100%);
}
.audio-player {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  transition: transform 0.5s ease;
  .fold-icon {
    position: absolute;
    right: 250px;
    top: -40px;
    width: 30px;
    height: 30px;
    // animation-name: flash;
    // animation-iteration-count: infinite;
    // animation-direction: alternate;
    // animation-duration: 2.5s;
  }
  .audio-mock-player {
    position: relative;
    padding: 5px 20px 12px 20px;
    background: #f1f3f4;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .progress {
      position: absolute;
      top: -19px;
      left: 0;
    }
    .left {
      .song-infor {
        margin-left: 20px;
        display: flex;
        .song-img {
          width: 50px;
          height: 50px;
          border-radius: 5px;
          background-color: pink;
          overflow: hidden;
          .x-img {
            width: 100%;
            height: 100%;
          }
        }
        .song-right {
          margin-left: 5px;
          .song-name {
            font-family: PingFangSC-Regular;
            font-size: 13px;
            text-align: left;
            font-weight: 400;
            margin-bottom: 2px;
          }
          .bottom {
            display: flex;
            align-items: center;
            .current {
              font-family: PingFangSC-Regular;
              font-size: 12px;
              text-align: left;
              font-weight: 400;
            }
            .duration {
              opacity: 0.6;
              font-family: PingFangSC-Regular;
              font-size: 12px;
              text-align: left;
              font-weight: 400;
              margin-right: 16px;
            }
          }
        }
      }
    }
    .center {
      display: flex;
      justify-content: center;
      align-items: center;
      ::v-deep .ant-dropdown-link {
        margin-right: 35px;
      }
      .play-model {
        width: 20px;
        height: 20px;
        margin-top: 6px;
      }
      .preicon {
        width: 25px;
        height: 25px;
      }
      .play-sty {
        margin: 0 35px;
        width: 35px;
        height: 35px;
      }
      .vulumn {
        position: relative;
        margin-left: 35px;
        margin-top: 6px;
      }
    }
    .right {
      display: flex;
      .collect {
        width: 20px;
        height: 20px;
        margin-right: 35px;
      }
    }

    .closeicon {
      position: absolute;
      right: -10px;
      top: -10px;
      width: 20px;
      height: 20px;
    }
  }
}
</style>
